package top.hepingan.java.Aiconfig;


import com.fasterxml.jackson.databind.ObjectMapper;
import jakarta.annotation.Resource;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Component
public class ChatHistoryRedis {

    @Resource
    private RedisTemplate<String, Object> redisTemplate;

    private final ObjectMapper objectMapper = new ObjectMapper();

    /**
     * 保存聊天记录
     *
     * @param deviceCode 设备码
     * @param userMsg    用户消息
     * @param aiReply    AI 回复
     * @throws Exception JSON 序列化异常
     */
    public void saveChat(String deviceCode, String userMsg, String aiReply) throws Exception {
        // 构建记录
        Map<String, Object> record = new HashMap<>();
        record.put("user_msg", userMsg);
        record.put("ai_reply", aiReply);
        record.put("create_time", System.currentTimeMillis());

        // Redis Key
        String key = "chat:" + deviceCode;

        // 序列化为 JSON
        String json = objectMapper.writeValueAsString(record);

        // 保存到 Redis List 左侧
        redisTemplate.opsForList().leftPush(key, json);
    }

    /**
     * 获取聊天记录
     *
     * @param deviceCode 设备码
     * @return List<Map<String, Object>> 聊天记录列表
     */
    public List<Map<String, Object>> showHistory(String deviceCode) {
        String key = "chat:" + deviceCode;

        List<Object> rawList = redisTemplate.opsForList().range(key, 0, -1);
        if (rawList == null || rawList.isEmpty()) return Collections.emptyList();

        List<Map<String, Object>> result = new ArrayList<>();
        for (Object raw : rawList) {
            try {
                if (raw instanceof String json) {
                    result.add(objectMapper.readValue(json, Map.class));
                } else {
                    result.add(objectMapper.convertValue(raw, Map.class));
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return result;
    }
}
